<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-position="labelPosition"
           :class="isEdit?'':'formItem'"
  >
    <!--商业险信息-->
    <el-card class="box-card" shadow="never">

      <div slot="header" class="header-card">
        <span class="header-card-title">商业险信息</span>
      </div>

      <el-row :gutter="24">

        <el-col :span="8">
          <el-form-item label="租赁禀议保险公司:" v-if="isShow" prop="rentInsuranceCompany">
            <el-input v-model="ruleForm.rentInsuranceCompany" v-if="isEdit" disabled></el-input>
            <span v-else>{{ ruleForm.rentInsuranceCompany }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="投保渠道:" v-if="isShow" prop="insuranceChannels">
            <el-select v-model="ruleForm.insuranceChannels" v-if="isEdit" style="width: 100%;" disabled>
              <el-option v-for="v in dict.type.insurance_channels" :key="v.value" :label="v.label"
                         :value="Number(v.value)">
              </el-option>
            </el-select>
            <span v-else>{{ selectDictLabel(dict.type.insurance_channels, ruleForm.insuranceChannels) }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="被保险人:" v-if="isShow">
            <el-input v-model="ruleForm.syxInsuredName" v-if="isEdit" placeholder="请输入被保险人"></el-input>
            <span v-else>{{ ruleForm.syxInsuredName }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险公司:" prop="syxCompany" v-if="isShow">
            <!-- <el-input v-model="ruleForm.syxCompany" v-if="isEdit" placeholder="请输入商业险公司"></el-input> -->
            <insurance-select businessTypeCode="5" :companyId="ruleForm.syxCompanyId"
                              placeholder="请选择商业险公司" v-if="isEdit" @change="handleChange"/>
            <span v-else>{{ ruleForm.syxCompany }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险公司编码:" prop="syxCompanyCode" v-if="isShow">
            <el-input v-model="ruleForm.syxCompanyCode" disabled v-if="isEdit"
                      placeholder="请输入商业险公司编码"></el-input>
            <span v-else>{{ ruleForm.syxCompanyCode }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8" v-if="ruleForm.insuranceVoList.length === 1 && ruleForm.insuranceChannels == '3'">
          <el-form-item label="商业险保单号:" prop="syxPolicyCode">
            <el-input v-model="ruleForm.syxPolicyCode" v-if="isEdit" placeholder="请输入商业险保单号"></el-input>
            <span v-else>{{ ruleForm.syxPolicyCode }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险起保日:" prop="syxExpectBeginTime" v-if="isShow">
            <el-date-picker v-model="ruleForm.syxExpectBeginTime" type="date" placeholder="请选择商业险起保日"
                            v-if="isEdit" @change="handleTime"
                            value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else>{{ ruleForm.syxExpectBeginTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险到期日:" prop="syxExpectEndTime" v-if="isShow">
            <el-date-picker v-model="ruleForm.syxExpectEndTime" type="date" placeholder="请选择商业险到期日"
                            v-if="isEdit"
                            value-format='yyyy-MM-dd' style="width: 100%;">
            </el-date-picker>
            <span v-else>{{ ruleForm.syxExpectEndTime }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="商业险性质:" prop="syxInsuranceType" v-if="isShow">
            <el-select v-model="ruleForm.syxInsuranceType" v-if="isEdit" style="width: 100%;"
                       @change="handleType"
                       placeholder="请选择商业险性质">
              <el-option label="运营" value="1">
              </el-option>
              <el-option label="非运营" value="2">
              </el-option>
            </el-select>
            <span v-else>{{
                ruleForm.syxInsuranceType == 1 ? '运营' : ruleForm.syxInsuranceType == 2 ? '非运营' : ''
              }}</span>
          </el-form-item>
        </el-col>

        <!--        <el-col :span="8">-->
        <!--          <el-form-item label="商业险保费:" prop="syxAmount" v-if="isShow">-->
        <!--            <el-input v-model="ruleForm.syxAmount" :disabled="[2,3].includes(Number(ruleForm.insuranceChannels))"-->
        <!--                      v-if="isEdit"-->
        <!--                      @change="changeAmount('syxAmount')"-->
        <!--                      placeholder="请输入商业险保费"></el-input>-->
        <!--            <span v-else>{{ format_thousand(ruleForm.syxAmount) }}</span>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->

        <el-col style="margin-bottom: 8px;">
          <div style="padding-bottom:8px;font-size: 16px;">保险套餐</div>
          <el-table :data="ruleForm.businessList" border size='mini'>
            <el-table-column align="center" type="index" label="序号"/>

            <el-table-column label="操作" v-if="ruleForm.insuranceChannels === 3" width="100">
              <template #default="{row, $index}">
                <e-button type="text" v-if="row.boole" icon="eel-icon-plus"
                          @click="handleDle($index)">删除
                </e-button>
              </template>
            </el-table-column>

            <el-table-column align="center" prop="insuranceProName" label="商业险种"/>
            <el-table-column align="center" prop="insuranceQuota" label="保额/万元"
                             v-if="ruleForm.insuranceChannels === 3">
              <template #default="{row , $index}">
                <template  v-if="isEdit">
                  <el-input v-model="row.insuranceQuota"
                            v-if="typeof row.insuranceQuota === 'number'"
                            v-thousand
                            @change="changeTable(row, $index, 'insuranceQuota')" size="mini"
                            placeholder="请输入保额/万元"/>
                   <el-input v-model="row.insuranceQuota"
                              v-else
                              @change="changeTable(row, $index, 'insuranceQuota')" size="mini"
                              placeholder="请输入保额/万元"/>
                </template>

                <span v-else>
                 <span v-if="typeof row.insuranceQuota === 'number'">
                  {{format_thousand( row.insuranceQuota) || '--' }}
                </span>
                <span>
                  {{row.insuranceQuota}}
                </span>
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="insuranceQuota" label="保额/万元" v-else>
            </el-table-column>
            <el-table-column align="center" label="保险费用/元">
              <template #default="{row,$index}">
                <el-form-item class="formTable" :prop="'businessList.'+$index+'.insurancePrice'"
                              :rules="{required: isEdit,  trigger: 'blur'}">
                  <el-input v-if="isEdit" v-model="row.insurancePrice"
                            placeholder="请输入保险费用/元" v-thousand
                            @change="changeTable(row, $index, 'insurancePrice')" size="mini"/>
                  <span v-else>{{ format_thousand(row.insurancePrice) }}</span>
                </el-form-item>

              </template>
            </el-table-column>
            <template v-slot:append
                      v-if="ruleForm.insuranceChannels === 3 &&
                      ruleForm.businessList.length !== dict.type.insurance_project.length">
              <div class="flex-xy-center" style="height: 40px">
                <div style="display: flex">
                  <e-button type="text" style="margin-right: 20px" icon="eel-icon-plus"
                            v-if="insuranceProName !== ''"
                            @click="addDecoration">添加
                  </e-button>
                  <el-select v-model="insuranceProValue" v-if="isEdit" placeholder="请选择商业险种"
                             style="width: 100%;" @change="handleInsuranceProName">
                    <el-option v-for="v in dict.type.insurance_project" :key="v.value" :label="v.label"
                               :disabled="v.disabled"
                               :value="v.value">
                    </el-option>
                  </el-select>
                </div>

              </div>
            </template>
          </el-table>
        </el-col>

        <el-col :span="24">
          <el-form-item label="商业险保单:" prop="syxPolicyUrl" v-if="ruleForm.insuranceVoList.length === 1 && ruleForm.insuranceChannels == 3">
            <image-common v-model="ruleForm.syxPolicyUrl" :disabled="!isEdit" :limit="20" :upType="2"/>
          </el-form-item>
        </el-col>

      </el-row>

    </el-card>
  </el-form>
</template>

<script>
import {effectDate} from "@/utils/libs/effectDate.js"

export default {
  mame: "commerciaInsurance", // <!--商业险信息-->
  dicts: ["insurance_channels", "insurance_project"],


  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },

  components: {
    insuranceSelect: () => import('../insuranceSelect')
  },

  computed: {
    ruleForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key)
            }
            that.handleData(key, value)
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.state === 'write') {
        return 'top'
      } else {
        return 'right'
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool
    }
  },

  watch: {
    value: {
      handler(newValue) {
        if (newValue) {
          if (newValue.syxInsuranceType) {
            this.$nextTick(() => {
              this.$refs.ruleForm.clearValidate('syxInsuranceType')
            })
          }

        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    var start = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
          that.ruleForm.syxExpectBeginTime,
          that.ruleForm.syxExpectEndTime,
          '商业险起保日',
          '商业险到期日'
      )
    };
    var end = (rule, value, callback) => {
      let that = this
      effectDate(rule, value, callback,
          that.ruleForm.syxExpectBeginTime,
          that.ruleForm.syxExpectEndTime,
          '商业险起保日',
          '商业险到期日'
      )
    };

    var syxCode = (rule, value, callback) => {
      let that = this;
      if (value === " " || value === null) {
        callback(new Error("请输入保单号"));
      } else {
        if (value === that.ruleForm.jqxPolicyCode) {
          callback(new Error("商业险保单号冲突,请核实"));
        } else {
          callback();
        }
      }
    };


    return {
      isShow: true,
      obj: {},
      rules: {
        //商业险信息
        syxCompany: [
          {required: this.state === 'write', message: "请选择商业险公司", trigger: "blur"},
        ],
        syxPolicyCode: [
          {required: this.state === 'write', validator: syxCode, trigger: "blur"},
        ],
        syxCompanyCode: [
          {required: this.state === 'write', message: "请输入商业险公司编码", trigger: "blur"},
        ],
        syxExpectBeginTime: [
          {required: this.state === 'write', validator: start, trigger: "blur"},
        ],
        syxExpectEndTime: [
          {required: this.state === 'write', validator: end, trigger: "blur"},
        ],
        syxInsuranceType: [
          {required: this.state === 'write', message: "请选择商业险性质", trigger: "blur"},
        ],
        syxAmount: [
          {required: this.state === 'write', message: "请输入商业险保费", trigger: "blur"},
        ],
        syxPolicyUrl: [
          {required: this.state === 'write', message: "请输入商业险保单", trigger: "blur"},
        ]
      },
      insuranceProName: '',
      insuranceProValue: '',
      insuranceProject: [],
    };
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      this.ruleForm?.syxExpectBeginTime && this.handleTime(this.ruleForm?.syxExpectBeginTime)
    })
  },
  methods: {
    handleType(val) {
      if (val) {
        this.value.jqxInsuranceType = this.ruleForm.jqxInsuranceType = val
        this.value.syxInsuranceType = this.ruleForm.syxInsuranceType = val

      }
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr()
            reject();
          }
        });
      });
    },

    locateToErr() {

      this.$nextTick(() => {
        let isError = document.getElementsByClassName('is-error')
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: 'center',
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: 'smooth',
        })
      })
    },
    // 店保金额格式
    changeTable(row, key, field) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      let _value
      if (row[field]) {
        if (msg.test(Number(row[field]))) {
          if (Number(row[field]) >= 0) {
            _value = row[field].toString().match(/^\d+(?:\.\d{0,2})?/)[0];
            row[field] = _value;
          } else {
            row[field] = "";
          }
        } else {
          row[field] = "";
        }
      }
      let key_ = this.dict.type.insurance_project.map(a => {
        if (Number(row.insuranceProCode) === Number(a.value)) {
          return a.raw.remark
        }
      }).filter(a => a)[0]
      for (let i = 0; i < this.value.insuranceVoList.length; i++) {
        this.$set(this.value.insuranceVoList[i], key_, _value)
      }
      //客户自购计算商业险保费
      if ([2, 3].includes(Number(this.ruleForm.insuranceChannels)) && field === 'insurancePrice') {
        this.value.syxAmount = this.handleCount()
        this.handleSyxAmount()
      }
    },

    handleSyxAmount() {
      for (let i = 0; i < this.value.insuranceVoList.length; i++) {
        this.value.insuranceVoList[i].syxAmount = 0
        this.value.insuranceVoList[i].syxAmount =
            Number(this.value.insuranceVoList[i].szxPrice) +
            Number(this.value.insuranceVoList[i].ckPrice) +
            Number(this.value.insuranceVoList[i].jsyPrice) +
            Number(this.value.insuranceVoList[i].csxPrice) +
            Number(this.value.insuranceVoList[i].clPrice) +
            Number(this.value.insuranceVoList[i].hhxPrice) +
            Number(this.value.insuranceVoList[i].qtPrice) +
            Number(this.value.insuranceVoList[i].zzfwPrice)
      }
    },

    handleCount() {
      let num = 0
      this.value.syxAmount = 0
      for (let i = 0; i < this.value.businessList.length; i++) {
        num += Number(this.value.businessList[i].insurancePrice)
      }
      return num
    },

    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.ruleForm[str])) {
        this.ruleForm[str] = "";
      } else {
        this.ruleForm[str] = this.ruleForm[str]
            .toString()
            .match(/^\d+(?:\.\d{0,2})?/)[0];
      }

    },

    //商业险公司
    handleChange(val) {
      this.value.syxCompanyCode = val.code
      this.value.syxCompany = val.name
      this.value.syxCompanyId = val.id
      this.value.jqxCompanyCode = val.code;
      this.value.jqxCompany = val.name;
      this.value.jqxCompanyId = val.id;
      this.value.insuranceVoList.forEach(item => {
        this.$set(item, 'syxCompanyCode', val.code)
        this.$set(item, 'syxCompany', val.name)
        this.$set(item, 'syxCompanyId', val.id)
        this.$set(item, "jqxCompanyCode", val.code);
        this.$set(item, "jqxCompany", val.name);
        this.$set(item, "jqxCompanyId", val.id);
      })
      this.$refs.ruleForm.clearValidate('syxCompany')
      this.$refs.ruleForm.clearValidate('syxCompanyCode')
    },


    valid() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate((valid) => {
          resolve(valid);
        });
      });
    },

    handleInsuranceProName(val) {
      let index = this.ruleForm.businessList.findIndex(a => Number(a.insuranceProCode) === Number(val))
      if (index !== -1) {
        this.insuranceProName = ''
        this.insuranceProValue = ''
        this.$message({
          message: '商业险种已有，请重新选择',
          type: 'warning'
        });
        return
      }
      let str = this.dict.type.insurance_project.map(a => {
        if (val == a.value) {
          return a.label
        }
      }).filter(a => a)[0]
      this.insuranceProName = str
      this.insuranceProValue = val
    },

    addDecoration() {

      let obj = {
        createBy: null,
        createTime: null,
        delFlag: null,
        id: null,
        insuranceId: null,
        insuranceManageId: null,
        insurancePrice: null,
        insuranceProCode: Number(this.insuranceProValue),
        insuranceProName: this.insuranceProName,
        insuranceQuota: "",
        updateBy: null,
        updateStatus: null,
        updateTime: '',
        boole: true
      }
      this.ruleForm.businessList.push(obj)
      this.insuranceProName = ''
      this.insuranceProValue = ''
      this.$forceUpdate()
    },

    handleDle(index) {
      this.ruleForm.businessList.splice(index, 1)
    },

    //取消表单效验
    handleClearValidate(str) {
      this.$refs.ruleForm.clearValidate(str);
    },


    handleData(key, value) {
      this.value.insuranceVoList.forEach(item => {
        if (typeof (item) !== "string") {
          item[key] = value
        } else {
          item[key] = value
        }

      })
    },

    handleTime(val) {
      let timeDate = this.addOneMonth(val, 12)
      this.$set(this.ruleForm, 'syxExpectEndTime', timeDate)
    },

    addOneMonth(dateString, month) {
      const date = new Date(dateString);
      date.setMonth(date.getMonth() + Number(month));
      date.setDate(date.getDate() - 1)
      return date.toISOString().split('T')[0]; // 返回YYYY-MM-DD格式的日期字符串
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";
</style>


